from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.views import generic
from django.contrib.admin.views.decorators import staff_member_required
from django.template.loader import render_to_string
from django.http import HttpResponse
from django.conf import settings
import weasyprint

from . import forms
from cart.cart import Cart
from order.services.order import Order
from . import models as order_models


class CreatingOrder(generic.View):

    """ Обработчик для создания заказа """

    def get(self, request):

        user_cart = Cart(request)
        form = forms.CreateOrderForm()
        context = {'form': form,
                   'user_cart': user_cart}

        return render(request, 'order/create.html', context)

    def post(self, request):

        bound_form = forms.CreateOrderForm(request.POST)

        if bound_form.is_valid():

            created_order = bound_form.save()
            user_order = Order(request)
            user_order.add(created_order)
            context = {'order': created_order}
            return render(request, 'order/created.html', context)


@staff_member_required
def admin_order_pdf(request, id):

    """ Формируем файл pdf """

    order = get_object_or_404(order_models.Order, id=id)
    html = render_to_string('order/pdf.html', {'order': order})

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename=order_{}.pdf'.format(order.id)
    weasyprint.HTML(string=html) \
            .write_pdf(response, stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + 'css/pdf.css')])

    return response
